package com.codergd.gra.utils;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;


@Component
public class FileTran {
    /**
     * 参数：文件，本地目录路径
     * 返回：新的文件名，以UUID为名
     */
    public String FileTran(MultipartFile file,String path) {
        //获取上传文件名,包含后缀
        String originalFilename = file.getOriginalFilename();
        if(file.getSize() > 2 * 1024 * 1024) {
            return null;
        }
        System.out.println("get file name,suffix:" + originalFilename);
        if(originalFilename.equals("")) {
            return null;
        }
        //获取后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println("get suffix:" + substring);
        if(!substring.equals(".jpg") && !substring.equals(".png") && !substring.equals(".pdf")) {
            return null;
        }
        //保存的文件名
        String dFileName = UUID.randomUUID() + substring;
        // ().replaceAll("-","");
        System.out.println("file name:" + dFileName);
        //保存路径
        //springboot 默认情况下只能加载 resource文件夹下静态资源文件
        // String path = "D:\\360downloads\\tempimg\\";
        //生成保存文件
        File uploadFile = new File(path + dFileName);
        System.out.println(uploadFile);
        //将上传文件保存到路径
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
//            System.out.println("cannot transfer the file correctly");
            e.printStackTrace();
        }
        return dFileName;
    }
}
